package com.dlc.commonlibrary.ble;

import android.os.Handler;
import android.os.Looper;
import com.dlc.commonlibrary.utils.LogPlus;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2017/7/19 0019.
 */

public class BleWorkerFind {

    private ReadCallback mCallback;
    private final StringBuilder mStringBuilder;
    private final AtomicInteger mReadNum;
    private final AtomicBoolean mStopped;
    private final AtomicInteger mErrorNumber;//长度小于14的数据长度
    private  int TYPE = 1;//1 代表正在读取，3 代表读取数据长度，2 代表读取手持机本身数据
    private ArrayList<String> rfidsList ;
    private int cashCount = 0;
    private final Handler mHandler;

    public interface ReadCallback {

        void onReceiveData(ArrayList<String> rfList, int readNum);
        void onReceiveRunning(String data);

        void onDeviceDisconnected();
    }

    public BleWorkerFind() {
        mStringBuilder = new StringBuilder();
        mReadNum = new AtomicInteger();
        mStopped = new AtomicBoolean();
        mErrorNumber = new AtomicInteger();
        mHandler = new Handler(Looper.getMainLooper());
    }

    public void setCallback(ReadCallback callback) {
        mCallback = callback;
    }

    public void check() {
        mStringBuilder.delete(0, mStringBuilder.length());
        mReadNum.set(0);
        mErrorNumber.set(0);
        mStopped.set(false);
        cashCount = 0;
        rfidsList = new ArrayList<>();
        TYPE = 1;
       // doCheck();
        getData();
    }



    private void getData(){

        if (RRUA100API.getInstance().getConnectDevice()!= null){
            RRUA100API.getInstance().A100_readStop();
            RRUA100API.getInstance().A100_setAllTagReport(true);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    RRUA100API.getInstance().A100_clear_inventory();
                    RRUA100API.getInstance().A100_setBuzzerVolume(1);
                    RRUA100API.getInstance().A100_readStart();
                }
            },500);

            RRUA100API.getInstance().readValue(new RRUA100API.BleCallBack() {
                @Override
                public void readDatas(String data,int type) {
                    if (type == 1||type == 2) {
                        rfidsList.add(data);
                        if (type == 1) {
                            if (mCallback != null) {
                                final String finalData = data;
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        mCallback.onReceiveRunning(finalData);
                                    }
                                });
                            }
                        }
                        LogPlus.e("蓝牙数据=" + data+"==蓝牙数据 count=" + rfidsList.size() + "");
                    }else {
                        if (TYPE == 3) {
                            mStopped.set(true);
                            data = data.replaceAll("\r|\n| ", "");
                            cashCount = Integer.parseInt(data);
                            judgeData(cashCount);
                        }else if (TYPE == 2){
                            judgeData(cashCount);
                        }
                    }
                }
            });
        } else { //跳去连接页面
            if (mCallback != null) {
                mCallback.onDeviceDisconnected();
            }
        }
    }

    private void judgeData(int cashCount) {
        mErrorNumber.set(0);
        if (rfidsList .size() > 0) {
            rfidsList = removeDuplicateWithOrder(rfidsList);
        }
        if (rfidsList.size() == cashCount || mReadNum.get() > 3) {//获取到的缓存区数量相等或者是直接获取缓存数据
            final ArrayList<String> mList = new ArrayList<>();
            for (String str : rfidsList) {
                if (str.length() > 14) {
                    str = str.substring(str.length() - 12, str.length());
                    mList.add(str);
                }else {
                    mErrorNumber.incrementAndGet();
                }
            }
            if (mCallback != null) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mCallback.onReceiveData(mList, mReadNum.get());
                    }
                });
            }

        } else {
            //ToastUtil.show(getContext(),"获取的数量不对应，直接获取读到的缓存rfid");
            mReadNum.incrementAndGet();
            TYPE = 2;
            rfidsList.clear();
            RRUA100API.getInstance().A100_getSyncTagList();
        }


    }
    public  ArrayList removeDuplicateWithOrder(ArrayList list) {
        Set set = new HashSet();
        ArrayList newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext();) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        return newList;
    }
    public void cancelCheck() {
       // BleHelper.getInstance().write(BleConstant.API_END_READ);
        RRUA100API.getInstance().A100_readStop();
        //如果1秒钟内，没有接到停止读取命令，就认为是蓝牙断开
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (TYPE ==1) {
                    TYPE = 3;
                    RRUA100API.getInstance().A100_getSyncTagListNum();
                }
            }
        },500);
        RRUA100API.getInstance().A100_setBuzzerVolume(0);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!mStopped.get()) {
                    if (mCallback != null) {
                        mCallback.onDeviceDisconnected();
                    }
                }
            }
        }, 2000);
    }


}
